import React, { useState, useEffect, useRef } from "react";
import { Tag, Button, Table, Pagination, Typography, Popconfirm, message, Tabs } from 'antd';
import type { TableColumnsType, PaginationProps } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import Common from "@/components/common/index"
import { placeRoute, affirmByIds } from "@/common/api"
import SendDetail from "../intelligent/detail";
const Plan: React.FC = () => {
    useEffect(() => {
        getData()
    }, []);
    const [loadings, setLoadings] = useState<boolean>(false);
    const [tableData, setTableData] = useState<any[]>([]);
    const [data, setData] = useState<any>(null)
    const getData = () => {
        let param = {
            pageSize: pageSizeRef.current,
            pageNum: pageNumRef.current,
            affirmFlag: activeKey
        }
        setLoadings(true)
        placeRoute(param).then((res: any) => {
            setLoadings(false)
            if (res.success) {
                setTableData(res.data.records)
                total.current = res.data.total
            } else {

            }
        })
    }
    const detail = (record: any) => {
        setData({ data: [...record.detailList], type: 2 })
    }
    //路线确认
    const lineSure = (record: any) => {
        affirmByIds({ ids: record.id }).then((res: any) => {
            if (res.success) {
                message.success(res.message)
                getData()
            } else {
                message.error(res.message)
            }
        })
    }
    const columns: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            align: 'center' as const,
            onCell: () => ({ style: { textAlign: 'center' } }),
            render: (_text, _record, index) => index + 1,
        },
        {
            title: '配送路线',
            dataIndex: 'placeWay',
            width: 200,
        },
        {
            title: '配送方式',
            dataIndex: 'markType',
            width: 120,
            render: (text) => {
                let color = '';
                if (text == '拼车') {
                    color = '#7BAD8D';
                } else if (text == '整车') {
                    color = '#758DD1';
                }
                else if (text == '待拼车') {
                    color = '#F7B707';
                }
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '配载(吨)',
            dataIndex: 'stowage',
            width: 120,
        },
        {
            title: '配送重量(吨)',
            dataIndex: 'totalLoad',
            width: 120,
        },
        {
            title: '总距离(km)',
            dataIndex: 'totalDistance',
            width: 120,
        },
        {
            title: '可补偿量',
            dataIndex: 'monthPlanFills',
            width: 150,
        },
        {
            title: '当前状态',
            dataIndex: 'affirmFlag',
            width: 120,
            onCell: (record) => ({
                style: {
                    color: record.affirmFlag === 0 ? 'red' : 'green',
                    cursor: 'pointer',
                },
            }),
            render: (_: any, record) => {
                return record.affirmFlag === 0 ? '未确认' : '已确认'
            },
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            width: 200,
            render: (_: any, record) => {
                return <>
                    <Typography.Link onClick={() => detail(record)} style={{ marginRight: 16 }}>
                        详情
                    </Typography.Link>

                    {record.affirmFlag == 0 && <Popconfirm
                        title="是否确认当前路线？"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => lineSure(record)}
                    >
                        <Typography.Link style={{ color: '#1677FF' }}>路线确认</Typography.Link>
                    </Popconfirm>}


                </>

            },
        },

    ];
    const [activeKey, setActiveKey] = useState('1');  //tab页
    const tabChange = (e: string) => {
        setActiveKey(e);
    };
    useEffect(() => {
        pageNumRef.current = 1;
        setCurrent(1);
        getData();
    }, [activeKey]);
    const download = async () => {
        let str = `affirmFlag=${activeKey}`
        if (process.env.NODE_ENV == "development") {
            window.location.href = `http://192.168.10.31:8611/api/marketShar/import?${str}`;
        } else {
            const host = window.location.protocol + "//" + window.location.host;
            window.location.href = `${host}/api/marketShar/import?${str}`;
        }
    }
    const getTable = () => {
        return <div style={{ height: '90%', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
                <Tabs
                    type="card"
                    items={[{ label: '已确认', key: '1' }, { label: '未确认', key: '0' }]}
                    activeKey={activeKey}
                    onChange={tabChange}
                />
                <Button icon={<DownloadOutlined />} type="primary" onClick={download} style={{ marginBottom: "14px" }}>导出</Button>
            </div>
            <Table
                columns={columns}
                dataSource={tableData}
                scroll={{ x: 'max-content' }}
                pagination={false}
                sticky={true}
                style={{ flex: '1', overflowY: 'auto', overflowX: 'hidden' }}
                rowKey="id"
                loading={loadings}
            />
        </div>






    }
    const freshList = () => {
        getData()
    }


    const total = useRef(0);
    const pageNumRef = useRef(1);
    const pageSizeRef = useRef(10);
    const [current, setCurrent] = useState<number>(1);
    const onChange: PaginationProps['onChange'] = (page, pageSize) => {
        pageNumRef.current = page;
        pageSizeRef.current = pageSize;
        setCurrent(page)
        getData()
    }
    const getPagination = () => {
        return <><Pagination
            size="small"
            total={total.current}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={onChange}
            current={current}
        />
            <SendDetail data={data} freshList={freshList} />
        </>
    }
    return <Common table={getTable()} paginations={getPagination()} />
}

export default Plan